package vms.data;

import java.util.Hashtable;

import net.Downloader;
import net.IDownloader;
import vms.Constants;
import vms.Settings;

import android.util.Log;

import com.vms.data.CheckerLocation;
import com.vms.data.GSMNetworkInfo;

public class CheckerJob extends Thread implements IDownloader {
	public static final String SIGN_GSM = "gsm";
	public static final String SIGN_INTERNET = "data";
	public static final String SIGN_APPS = "app";
	public static final String SIGN_LINK_INFO = "linkinfo";
	public static final String SIGN_LINK = "link";
	public static final String SIGN_LINK_UPDATE = "linkupdate";
	public static final String SIGN_UPDATE_DATA = "dataup";

	private boolean stop = false;
	private Downloader mDownloader;

	private long lastCheck = -1;

	private boolean isRunning = false;
	private String upspeed;
	private String downspeed;

	private String currentLink;

	public CheckerJob() {
		mDownloader = Downloader.getInstance();
		isRunning = false;
	}

	public void run() {
		try {

			isRunning = true;
			if (Constants.DEBUG)
				Log.i("INFO", "JOB RUNNING");
			if (LinkManager.getInstance().getLinks().size() <= 0) {
				loadLinks();
			}
			while (!stop) {
				try {

					Thread.yield();
					lastCheck = System.currentTimeMillis();

					startcheck();

					try {
						Thread.sleep(Settings.getInstance().getInterval() * 60 * 1000);
					} catch (Exception e) {
						// TODO: handle exception
					}

				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			isRunning = false;
			if (Constants.DEBUG)
				Log.i("INFO","JOB STOPPED");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void loadLinks() {
		Hashtable params = new Hashtable();
		mDownloader.getDataUsingHttp(SIGN_LINK, Constants.SERVER_DATA_LINKS, "POST", params, this);
	}

	private void startcheck() {
		if (Settings.getInstance().getCheckgsm() == 1) {
			checkgsmnetwork();
		} else if (Settings.getInstance().getCheckapps() == 1) {
			checkapplication();
		} else if (Settings.getInstance().getCheckdata() == 1) {
			checkinternet();
		}
	}

	private void checkgsmnetwork() {
		try {
			if (Constants.DEBUG)
				Log.i("NET","checkgsmnetwork");

			CheckerItem item = new CheckerItem();
			item.setCellid("" + GSMNetworkInfo.getInstance(null).getCellID());
			item.setLac("" + GSMNetworkInfo.getInstance(null).getLAC());
			item.setLatitude("" + CheckerLocation.getInstance(null).getLatitude());
			item.setLongitude("" + CheckerLocation.getInstance(null).getLongitude());
			item.setRxl("" + GSMNetworkInfo.getInstance(null).getSignalStreght());
			item.setType("" + GSMNetworkInfo.getInstance(null).getNetworkType());
			item.setBiterrorrate(GSMNetworkInfo.getInstance(null).getBitErrorRate());
			item.setEvdo(GSMNetworkInfo.getInstance(null).getEVDO());
			item.setEclo(GSMNetworkInfo.getInstance(null).getECIO());
			item.setNeighbourcells(GSMNetworkInfo.getInstance(null).getNeighbourCells());
			
			DataManager.instance.addGSMItem(item);
			Hashtable params = new Hashtable();
			// ke no da, duong nao cung set mac dinh trong cai kia roi
			mDownloader.getDataUsingHttp(SIGN_GSM, Constants.SERVER_DATA_NETWORK, "POST", params, this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void checkinternet() {
		if (Constants.DEBUG)
			Log.i("NET","checkinternet");

		Hashtable params = new Hashtable();
		// ke no da, duong nao cung set mac dinh trong cai kia roi
		params.put("content", getSampleData(1024 * Settings.getInstance().getDataSize()));
		params.put("size", "" + (Settings.getInstance().getDataSize() * 1024));
		mDownloader.getDataUsingHttp(SIGN_INTERNET, Constants.SERVER_DATA_DOWNLOAD, "POST", params, this);
	}

	private String getSampleData(int size) {
		StringBuffer buff = new StringBuffer();
		for (int i = 0; i < size; i++)
			buff.append("a");
		return buff.toString();
	}

	private void updateInternet() {
		try {
			if (Constants.DEBUG)
				Log.i("NET","updateInternet");

			InternetItem item = new InternetItem();
			item.setCellid("" + GSMNetworkInfo.getInstance(null).getCellID());
			item.setLac("" + GSMNetworkInfo.getInstance(null).getLAC());
			item.setLatitude("" + CheckerLocation.getInstance(null).getLatitude());
			item.setLongitude("" + CheckerLocation.getInstance(null).getLongitude());
			item.setRxl("" + GSMNetworkInfo.getInstance(null).getSignalStreght());
			item.setType("" + GSMNetworkInfo.getInstance(null).getNetworkType());
			item.setUpspeed(upspeed);
			item.setDownspeed(downspeed);
			item.setBiterrorrate(GSMNetworkInfo.getInstance(null).getBitErrorRate());
			item.setEvdo(GSMNetworkInfo.getInstance(null).getEVDO());
			item.setEclo(GSMNetworkInfo.getInstance(null).getECIO());
			item.setNeighbourcells(GSMNetworkInfo.getInstance(null).getNeighbourCells());
			
			DataManager.instance.addInternetItem(item);
			Hashtable params = new Hashtable();
			// ke no da, duong nao cung set mac dinh trong cai kia roi
			params.put("upspeed", "" + item.getUpspeed());
			params.put("downspeed","" +  item.getDownspeed());

			mDownloader.getDataUsingHttp(SIGN_UPDATE_DATA, Constants.SERVER_DATA_INTERNET, "POST", params, this);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void checkapplication() {
		if (Constants.DEBUG)
			Log.i("NET","checkapplication");
		currentLink = LinkManager.getInstance().getLink();
		if (currentLink == null) {
			checkinternet();
		} else {
			Hashtable params = new Hashtable();
			mDownloader.getDataUsingHttp(SIGN_LINK_INFO, currentLink, "POST", params, this, 1);
		}
	}

	private void updateApplication() {
		try {
			if (Constants.DEBUG)
				System.out.println("update_application");

			ApplicationItem item = new ApplicationItem();
			item.setCellid("" + GSMNetworkInfo.getInstance(null).getCellID());
			item.setLac("" + GSMNetworkInfo.getInstance(null).getLAC());
			item.setLatitude("" + CheckerLocation.getInstance(null).getLatitude());
			item.setLongitude("" + CheckerLocation.getInstance(null).getLongitude());
			item.setRxl("" + GSMNetworkInfo.getInstance(null).getSignalStreght());
			item.setType("" + GSMNetworkInfo.getInstance(null).getNetworkType());
			int time = (int) (System.currentTimeMillis() - startInternetUpConnect);
			item.setTime(time + "");
			item.setLink(currentLink);
			item.setBiterrorrate(GSMNetworkInfo.getInstance(null).getBitErrorRate());
			item.setEvdo(GSMNetworkInfo.getInstance(null).getEVDO());
			item.setEclo(GSMNetworkInfo.getInstance(null).getECIO());
			item.setNeighbourcells(GSMNetworkInfo.getInstance(null).getNeighbourCells());
			
			DataManager.instance.addApplicationItem(item);
			Hashtable params = new Hashtable();
			// ke no da, duong nao cung set mac dinh trong cai kia roi
			params.put("link", currentLink);
			params.put("time", time + "");

			mDownloader.getDataUsingHttp(SIGN_LINK_UPDATE, Constants.SERVER_DATA_APPLICATION, "POST", params, this);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void stopCheckJob() {
		this.stop = true;
	}

	public boolean isRunning() {
		return isRunning;
	}

	long startInternetUpConnect = -1;
	long startInternetDonwConnect = -1;

	public void DownloadChanged(String session, int status, String url, long total, long elapsed) {
		if (Constants.DEBUG) {
			Log.i("NET", session + ": " + status + "\t" + url);
		}
		switch (status) {
		case IDownloader.CONNECTING:
			if (SIGN_INTERNET.equals(session) || SIGN_LINK_INFO.equals(session)) {
				startInternetUpConnect = System.currentTimeMillis();
			}
			break;
		case IDownloader.CONNECTED:
			if (SIGN_INTERNET.equals(session)) {
				upspeed = getSpeed((int) (System.currentTimeMillis() - startInternetUpConnect), Settings.getInstance().getDataSize()) + "";
				startInternetDonwConnect = System.currentTimeMillis();
			}
			break;
		case IDownloader.DOWNLOADED:
			// System.out.println(new String(mDownloader.getData()));
			if (SIGN_LINK_INFO.equals(session)) {
				updateApplication();
			} else if (SIGN_LINK.equals(session)) {
				LinkManager.getInstance().parseLinks(mDownloader.getData());
			} else if (SIGN_GSM.equals(session)) {
				checkapplication();
			} else if (SIGN_LINK_UPDATE.equals(session)) {
				checkinternet();
			} else if (SIGN_INTERNET.equals(session)) {
				downspeed = getSpeed((int) (System.currentTimeMillis() - startInternetDonwConnect), mDownloader.getData().length / 1024) + "";
				updateInternet();
			}
			break;

		default:
			break;
		}
	}

	private int getMinute(int mili) {
		return mili / 1000;
	}

	/**
	 * Return speed as kb/s
	 * 
	 * @param mili
	 * @param size
	 * @return
	 */
	private String getSpeed(int mili, int size) {
		int sec = mili / 1000;
		if (sec == 0)
			sec = 1;
		int speed = size / sec;
		return speed + "";
	}
}
